<template>
    <div :id="editorId" class="ueditor-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, defineProps, defineEmits, nextTick } from 'vue';

interface UEditorInstance {
    getEditor(id: string, config: any): UEditorInstance;
    setContent(content: string): void;
    getContent(): string;
    getPlainTxt(): string;
    addListener(event: string, callback: (...args: any[]) => void): void;
    destroy(): void;
    setHeight(height: number): void;
    focus(): void;
    [key: string]: any;
}

declare global {
    interface Window {
        UE?: {
            getEditor: (id: string, config: any) => UEditorInstance;
        };
    }
}

const props = defineProps({
    modelValue: {
        type: String,
        default: '',
    },
    config: {
        type: Object as () => Record<string, any>,
        default: () => ({}),
    },
    height: {
        type: Number,
        default: 300,
    },
    showFullscreen: {
        type: Boolean,
        default: true,
    },
});

const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
    (e: 'ready', instance: UEditorInstance): void;
    (e: 'change', value: string): void;
    (e: 'error', error: Error): void;
}>();

const editorId = `ueditor-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
let editorInstance: UEditorInstance | null = null;
const isInitialized = ref(false);

// 构建包含全部工具的工具栏配置
const getToolbars = () => {
    const allToolbars = [
        // 工具栏配置，包含所有可能的工具按钮
        ['source', 'undo', 'redo', 'searchreplace', 'removeformat', 'cleardoc', 'formatmatch', 'autotypeset', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor',
            'fontfamily', 'fontsize', 'superscript', 'subscript', 'copy', 'cut', 'paste', 'pastetext', 'pasteplain', 'selectall', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',
            'indent', 'outdent', 'lineheight', 'paragraph', 'insertorderedlist', 'insertunorderedlist', 'horizontal', 'pagebreak', 'insertimage', 'emotion', 'insertvideo', 'insertaudio', 'link', 'unlink',
            'attachment', 'background', 'music', 'insertframe', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow',
            'insertcol', 'deletecol', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'tablesplit', 'tabledrag', 'insertcode', 'print', 'preview', 'fullscreen', 'help',
            'drafts', 'insertmap', 'charts', 'scrawl', 'wordimage', 'inserttemplate', 'webapp', 'gmap', 'edittip', 'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline',
            'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow',
        ],]

    // 根据配置移除全屏按钮（如果不需要）
    if (!props.showFullscreen) {
        const advancedIndex = allToolbars.findIndex(group => group.includes('fullscreen'));
        if (advancedIndex > -1) {
            allToolbars[advancedIndex] = allToolbars[advancedIndex].filter(item => item !== 'fullscreen');
        }
    }

    return allToolbars;
};

const getDefaultConfig = () => ({
    UEDITOR_HOME_URL: '/src/ueditor/',
    initialFrameWidth: '100%',// 宽度百分比
    initialFrameHeight: props.height,
    autoClearinitialContent: false,
    serverUrl: '/api/ueditor/upload',
    enableAutoSave: true,
    saveInterval: 5000,
    scaleEnabled: true,
    ...props.config,
    toolbars: getToolbars(),
});

const initEditor = () => {
    if (isInitialized.value) return;

    if (window.UE) {
        try {
            const finalConfig = getDefaultConfig();
            editorInstance = window.UE.getEditor(editorId, finalConfig);

            editorInstance.addListener('ready', () => {
                isInitialized.value = true;
                console.log('UEditor 初始化完成');
                if (props.modelValue) {
                    editorInstance?.setContent(props.modelValue);
                }
                emit('ready', editorInstance);
            });

            editorInstance.addListener('contentChange', () => {
                if (editorInstance) {
                    const content = editorInstance.getContent();
                    emit('update:modelValue', content);
                    emit('change', content);
                }
            });

            editorInstance.addListener('error', (error: Error) => {
                emit('error', error);
            });
        } catch (error) {
            emit('error', error as Error);
            console.error('UEditor 初始化失败:', error);
        }
    } else {
        const retryCount = ref(0);
        const retryInit = () => {
            if (retryCount.value < 10) {
                retryCount.value++;
                setTimeout(initEditor, 300);
            } else {
                emit('error', new Error('UEditor 加载超时，请检查资源是否引入'));
            }
        };
        retryInit();
    }
};

onMounted(() => {
    nextTick(() => {
        initEditor();
    });
});

watch(
    () => props.modelValue,
    (newVal) => {
        if (editorInstance && isInitialized.value && newVal !== editorInstance.getContent()) {
            editorInstance.setContent(newVal || '');
        }
    },
    { immediate: false }
);

watch(
    () => props.height,
    (newHeight) => {
        if (editorInstance && isInitialized.value) {
            editorInstance.setHeight(newHeight);
        }
    }
);

onBeforeUnmount(() => {
    if (editorInstance) {
        editorInstance.destroy();
        editorInstance = null;
        isInitialized.value = false;
        console.log('UEditor 已销毁');
    }
});

defineExpose({
    getContent: () => editorInstance?.getContent() || '',
    getPlainText: () => editorInstance?.getPlainTxt() || '',
    clearContent: () => {
        if (editorInstance) {
            editorInstance.setContent('');
        }
    },
    getInstance: () => editorInstance,
    focus: () => editorInstance?.focus(),
    isReady: () => isInitialized.value,
});
</script>

<style scoped>
.ueditor-container {
    width: 100%;
    height: 100%;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    transition: border-color 0.2s;
    box-sizing: border-box;
}

.ueditor-container:hover {
    border-color: #409eff;
}

:deep(.edui-container) {
    width: 100% !important;
    height: 100% !important;
}

:deep(.edui-editor) {
    border: none !important;
}

:deep(.edui-toolbar) {
  padding-top: 1px !important; 
  padding-bottom: 1px !important;
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}
</style>    